<template>
  <div class="new-retreat route-page" :class="$store.getters.isMobile ? 'isMobile' : ''">
    <section class="header">
      <a-page-header
        class="demo-page-header"
        :class="notBack ? 'hide-back' : ''" 
        style="border: 1px solid rgb(235, 237, 240)"
        :title="viewType == 'view' ? '退租协议' : '新建退租协议'"
        sub-title=""
        @back="() => $router.go(-1)"
      >
        <template #extra v-if="viewType == 'view'">
          <a-col>
            <a-button type="primary" ghost @click="createPrintModel">
              生成打印模板
            </a-button>
          </a-col>
        </template>
        <div style="display: flex; justify-content: space-between">
          <a-list item-layout="horizontal" style="width: 80%">
            <a-list-item>
              <a-list-item-meta>
                <template #avatar>
                  <!-- <a-avatar
                  src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"
                  size="large"
                /> -->
                  <FileTwoTone style="font-size: 36px" />
                </template>
                <template #title>
                  <a href="https://www.antdv.com/">
                    <span
                      style="font-weight: bold; color: #333333; font-size: 18px"
                    >
                      租客：{{ mainInfo.owner_name }}
                    </span>
                  </a>
                </template>
                <template #description>
                  <div style="font-weight: bold; color: #333333">
                    合同编号： {{ mainInfo.contract_number }}
                  </div>
                  <div
                    style="font-weight: bold; color: #333333"
                    v-if="templateDownloadInfo.fileUrl"
                  >
                    协议打印模板：
                    <a-button
                      type="link"
                      @click="downloadFile(templateDownloadInfo.fileUrl)"
                      >{{ templateDownloadInfo.fileName }}</a-button
                    >
                  </div>
                  <a-alert
                    v-show="timeoutDay > 0"
                    showIcon
                    :message="
                      '当前合同已过期' +
                      timeoutDay +
                      '天,如有延期退租行为可通过账单进行调整。'
                    "
                    type="info"
                    style="margin-top: 20px"
                  />
                </template>
              </a-list-item-meta>
            </a-list-item>
          </a-list>
          <div
            style="
              width: 20%;
              display: flex;
              flex-direction: column;
              align-items: flex-end;
            "
            v-if="viewType == 'view'"
          >
            <p style="margin-bottom: 5px">{{ summaryTotalStatus }}</p>
            <p style="font-size: 18px; color: #333333">
              ￥{{ Math.abs(summaryTotal).toFixed(2) }}
            </p>
          </div>
        </div>
      </a-page-header>
    </section>
    <section class="content">
      <a-row :gutter="12">
        <a-col :span="12" class="mt-10">
          <a-card size="small" title="退租信息">
            <a-form layout="vertical">
              <a-row :gutter="12">
                <a-col :span="12">
                  <a-form-item
                    label="退租类型"
                    v-bind="validateInfos.retreatType"
                  >
                    <a-select
                      v-model:value="modelRef.retreatType"
                      placeholder=""
                      :options="
                        retreatTypeList.map((item) => ({
                          value: item.key,
                          label: item.name,
                        }))
                      "
                      :disabled="viewType == 'view'"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item v-bind="validateInfos.retreatDate">
                    <template #label>
                      <span>退租日期</span>
                      <text-tip
                        :tips="[
                          '退租日期大于等于今天，则合同状态会改为“退租待执行”，等待第二天0点，即会自动变更为“已退租”。',
                          '退租日期小于今天，则会立即进行退租处理。与该合同相挂钩的功能，将会立即终止。',
                        ]"
                      />
                    </template>
                    <a-date-picker
                      v-model:value="modelRef.retreatDate"
                      format="YYYY-MM-DD"
                      placeholder=""
                      :open="endOpen"
                      @openChange="handleRetreatDateOpenChange"
                      @change="handleRetreatDateChange"
                      style="width: 100%"
                      :disabled="viewType == 'view'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="12">
                <a-col :span="12">
                  <a-form-item
                    label="工商注册地址变更日期"
                    v-bind="validateInfos.addressChangeDate"
                  >
                    <a-date-picker
                      v-model:value="modelRef.addressChangeDate"
                      placeholder=""
                      style="width: 100%"
                      :disabled="viewType == 'view'"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    label="协议签订日期"
                    v-bind="validateInfos.signDate"
                  >
                    <a-date-picker
                      v-model:value="modelRef.signDate"
                      :disabled-date="disabledStartDate"
                      format="YYYY-MM-DD"
                      placeholder=""
                      style="width: 100%"
                      :disabled="viewType == 'view'"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="12">
                <a-col :span="12">
                  <a-form-item
                    label="退租原因"
                    v-bind="validateInfos.retreatReason"
                  >
                    <a-select
                      v-model:value="modelRef.retreatReason"
                      placeholder=""
                      mode="multiple"
                      :options="
                        reasonList.map((item) => ({
                          value: item.id,
                          label: item.name,
                        }))
                      "
                      :disabled="viewType == 'view'"
                    >
                      <template #dropdownRender="{ menuNode: menu }">
                        <v-nodes :vnodes="menu" />
                        <a-divider style="margin: 4px 0" />
                        <div
                          style="
                            padding: 4px 8px;
                            cursor: pointer;
                            color: #1890ff;
                            text-align: center;
                          "
                          @mousedown="(e) => e.preventDefault()"
                          @click="() => (editVisible = true)"
                        >
                          添加
                        </div>
                      </template>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-card>
        </a-col>
        <a-col :span="12" class="mt-10">
          <a-card size="small" title="房源信息">
            <checked-build
              :content="buildBindInfo"
              :height="258"
              style="overflow-y: scroll"
            />
          </a-card>
        </a-col>
      </a-row>

      <!--   水电信息   -->
      <a-row :gutter="12" v-if="energyData.length">
        <a-col :span="24" class="mt-10">
          <a-card size="small" class="bill-card" title="水电表">
            <template #extra v-if="viewType == 'edit'">
              <a-space>
                <a-button @click="getEnergyData()">
                  <template #icon>
                    <SyncOutlined />
                  </template>
                  刷新
                </a-button>
              </a-space>
            </template>

            <a-table
              :columns="energyColumns"
              :data-source="energyData"
              :loading="energyLoading"
              :pagination="false"
              rowKey="id"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'energyType'">
                  <span style="margin-right: 6px">{{record.type_name}}</span>
                  <a-tag>{{record.payment_type_txt}}</a-tag>
                </template>
                <template v-if="column.key === 'action'">
                  <a-button type="link" @click.stop="getEnergyRead(record)">读表</a-button>
                  <a-button type="link" v-if="!record.payment_type" @click.stop="getEnergyReading(record)">抄表</a-button>
                  <a-button type="link" v-if="record.payment_type" @click.stop="getEnergyBill('pay', record)" :disabled="!record.canGeneratedOrder">{{`生成${record?.current_remaining < 0 ? '收' : '付'}款单`}}}</a-button>
                  <a-button type="link" v-else @click.stop="getEnergyBill('collect', record)" :disabled="!record.canGeneratedOrder">生成收款单</a-button>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
      <!--   账单   -->
      <a-row :gutter="12">
        <a-col :span="24" class="mt-10">
          <a-card size="small" class="bill-card">
            <template #title>
              <span>账单结算</span>
              <text-tip
                v-if="viewType == 'edit'"
                :tips="[
                  '退租后的账单将自动关闭，计费周期外的已结清账单不在此处显示',
                ]"
              />
              <text-tip
                v-else
                :tips="['退租后的账单将自动关闭，已结清账单不在此处显示']"
              />
              <!-- <text-tip
                :tips="[
                  '天平均是指单价最后都换算为天单价计算；月平均：指整月的时间段租金单价按月单价计算，不足整月的按换算的天单价计算。月单价=日单价*年天数/12，天单价=月单价*12/年天数。',
                ]"
                :iconType="'exclamation'"
              /> -->
            </template>
            <template #extra v-if="viewType == 'edit'">
              <a-button @click="showBillModal1" style="margin-right: 10px"
                >添加收款</a-button
              >
              <a-button @click="showBillModal2">添加付款</a-button>
            </template>

            <a-table
              :columns="billColumns"
              :data-source="billData"
              :loading="billLoading"
              :pagination="false"
              rowKey="id"
              :scroll="{ x: 'max-content' }"
              :customRow="billCustomRow"
            >
              <template #headerCell="{ title, column }">
                <template v-if="column.key === 'receivable_payment'">
                  <!-- 浏览模式下不展示tip提示 -->
                  <span> 应收付金额/原始应收付 </span>
                  <text-tip
                    v-if="viewType == 'edit'"
                    :tips="[
                      '已按租赁天数自动计算未满计费周期的账单，修改应收/付金额视作账单调整',
                    ]"
                  />
                </template>
                <template v-if="column.key === 'receivable_payment_date'">
                  <!-- 浏览模式下不展示tip提示 -->
                  <span> 应收/付日期 </span>
                  <text-tip
                    v-if="viewType == 'edit'"
                    :tips="[
                      '更改应付日期影响到滞纳金计算，请妥善操作；当涉及退款时，请合理设置应收/付日期',
                    ]"
                  />
                </template>
              </template>

              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'receivable_payment'">
                  <template v-if="viewType == 'view'">
                    <span>{{`${text}/${record.pre_receivable_payment}`}}</span>
                  </template>
                  <template v-else>
                    <a-input-number
                      id="inputNumber"
                      v-model:value="record.receivable_payment"
                      :min="0"
                      :precision="2"
                      style="width: 55%"
                      @change="onReceivableInput(record)"
                      :disabled="record.is_append"
                    />
                    <span style="width: 45%">
                      {{`/${record.pre_receivable_payment}`}}
                    </span>
                  </template>
                </template>
                <template v-if="column.key === 'need_latefee'">
                  <template v-if="viewType == 'view'">
                    <span>{{ text || '--' }}</span>
                  </template>
                  <template v-else>
                    <template v-if="record.latefee_status == 1 && record.start_need_latefee > 0">
                      <a-input-number
                        v-model:value="record.need_latefee"
                        :min="0"
                        :precision="2"
                        style="width: 100%"
                      />
                    </template>
                    <span v-else>{{ text || '--' }}</span>
                  </template>
                </template>
                <template v-if="column.key === 'cost_type_txt'">
                  <span>{{ text }}</span>
                  <template v-if="viewType == 'edit'">
                    <DeleteOutlined
                      v-if="record.is_append"
                      style="margin-left: 5px"
                      @click="deleteAppendRecord(index)"
                    />
                    <text-tip
                      :tips="['当前账单已具发票/收据，请谨慎调整账单价格']"
                      :iconType="'exclamation'"
                      v-else-if="record.issue_flag"
                    />
                  </template>
                </template>
                <template v-if="column.key === 'bill_type_txt'">
                  <a-tag color="green" v-if="record.bill_type == 1">收款</a-tag>
                  <a-tag color="orange" v-else>付款</a-tag>
                </template>
                <template v-if="column.key === 'actual_retreat'">
                  <template v-if="viewType == 'edit'">
                    <a-tag color="green" v-if="record.pay_type === 'income'">收</a-tag>
                    <a-tag color="orange" v-else>付</a-tag>
                  </template>
                  <span>{{ text }}</span>
                </template>
                <template v-if="column.key === 'actual_payment'">
                  <span>{{
                    record.actual_payment ? record.actual_payment : "0.00"
                  }}</span>
                </template>
                <template v-if="column.key === 'receivable_payment_date'">
                  <template v-if="viewType == 'view'">
                    <span>{{ text }}</span>
                  </template>
                  <template v-else>
                    <a-date-picker
                      v-model:value="record.receivable_payment_date"
                      format="YYYY-MM-DD"
                      valueFormat="YYYY-MM-DD"
                    />
                  </template>
                </template>
                <template v-if="column.key === 'carry_over'">
                  <a-tag color="green">入</a-tag>￥{{ record.into_amount || 0 }}
                  <span v-if="record.out_amount">
                     <a-tag color="red" style="margin-left: 8px">出</a-tag>￥{{ record.out_amount || 0 }}
                  </span>
                  <span v-if="record.into_amount || record.out_amount" style="margin-left: 4px; font-size: 12px" class="link" @click="viewCarryOver(record)">
                    查看
                  </span>
                </template>
                <template v-if="column.key === 'bill_number'">
                  <span :class="text ? 'link' : ''" @click.stop="viewBillDetail(record.id)">{{text || '--'}}</span>
                </template>
              </template>
            </a-table>
            <a-alert
              :message="billTotalStatus + Math.abs(billTotal).toFixed(2) + '元'"
              type="info"
            />
          </a-card>
        </a-col>
      </a-row>
      <!--   保证金   -->
      <a-row :gutter="12">
        <a-col :span="24" class="mt-10">
          <a-card size="small" title="保证金" class="bill-card">
            <a-table
              :columns="bondColumns"
              :data-source="bondData"
              :loading="bondLoading"
              :pagination="false"
              rowKey="id"
              :scroll="{ x: 'max-content' }"
              :customRow="bondCustomRow"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'receivable_payment_date'">
                  <template v-if="viewType == 'view'">
                    <span>{{ text }}</span>
                  </template>
                  <template v-else>
                    <a-date-picker
                      v-model:value="record.receivable_payment_date"
                      format="YYYY-MM-DD"
                      valueFormat="YYYY-MM-DD"
                    />
                  </template>
                </template>
                <template v-if="column.key === 'need_latefee'">
                  <template v-if="viewType == 'view'">
                    <span>{{ text || '--' }}</span>
                  </template>
                  <template v-else>
                    <template v-if="record.latefee_status == 1 && record.start_need_latefee > 0">
                      <a-input-number
                        v-model:value="record.need_latefee"
                        :min="0"
                        :precision="2"
                        style="width: 100%"
                      />
                    </template>
                    <span v-else>{{ text || '--' }}</span>
                  </template>
                </template>
                <template v-if="column.key === 'receivable_payment'">
                  <span>{{ text }}</span>
                </template>
                <template v-if="column.key === 'carry_over'">
                  <a-tag color="green">入</a-tag>￥{{ record.into_amount || 0 }}
                  <span v-if="record.out_amount">
                    <a-tag color="red" style="margin-left: 8px">出</a-tag>￥{{ record.out_amount || 0 }}
                  </span>
                  <span v-if="record.into_amount || record.out_amount" style="margin-left: 4px; font-size: 12px" class="link" @click="viewCarryOver(record)">
                    查看
                  </span>
                </template>
                <template v-if="column.key === 'forfeit_amount'">
                  <span>{{text || '--'}}</span>
                  <span v-if="text > 0" class="link" style="margin-left: 6px" @click="viewForfeit(record)">
                    查看记录
                  </span>
                </template>
                <template v-if="column.key === 'action'">
                  <a-button type="link" :disabled="record.receivable_payment <= 0" @click="forfeitBond(record)">罚没</a-button>
                </template>
                <template v-if="column.key === 'bill_number'">
                  <span class="link" @click.stop="viewBillDetail(record.id)">{{text}}</span>
                </template>
              </template>
            </a-table>
            <a-alert
              :message="bondTotalStatus + Math.abs(bondTotal).toFixed(2) + '元'"
              type="info"
            />
          </a-card>
        </a-col>
      </a-row>
      <!--   预存   -->
      <a-row :gutter="12">
        <a-col :span="24" class="mt-10">
          <a-card size="small" class="bill-card" title="预存费用">
            <a-table
              :columns="prestoreColumns"
              :data-source="prestoreData"
              :loading="prestoreLoading"
              :pagination="false"
              rowKey="id"
              :customRow="streamCustomRow"
            >
              <template #headerCell="{ title, column }">
                <template v-if="column.key === 'cost_type_txt'">
                  <span> 费用类型 </span>
                  <text-tip
                    :tips="[
                      '此处的费用类型为生成流水退款账单的费用类型，由管理员在收入流水列表页统一设置。',
                    ]"
                  />
                </template>
                <template v-if="column.key === 'remark'">
                  <span> 账单备注 </span>
                  <text-tip
                    :tips="[
                      '生成待退款收款单时的账单备注',
                    ]"
                  />
                </template>
              </template>
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'receivable_payment'">
                  <template v-if="viewType == 'view'">
                    <span>{{ text }}</span>
                  </template>
                  <template v-else>
                    <a-input-number
                      v-model:value="record.receivable_payment"
                      :min="0"
                      :precision="2"
                      style="width: 100%"
                      :max="Number(record.nomatch_price)"
                      @change="onPrestoreReceivableInput(record)"
                    />
                  </template>
                </template>
                <template v-if="column.key === 'actual_retreat'">
                  <template v-if="viewType == 'edit'">
                    <a-tag color="green" v-if="record.bill_type == 1">收</a-tag>
                    <a-tag color="orange" v-else>付</a-tag>
                  </template>
                  <span>{{ text }}</span>
                </template>
                <template v-if="column.key === 'actual_payment'">
                  <span>{{
                      record.actual_payment ? record.actual_payment : "0.00"
                    }}</span>
                </template>
                <template v-if="column.key === 'receivable_payment_date'">
                  <template v-if="viewType == 'view'">
                    <span>{{ text }}</span>
                  </template>
                  <template v-else>
                    <a-date-picker
                      v-model:value="record.receivable_payment_date"
                      format="YYYY-MM-DD"
                      valueFormat="YYYY-MM-DD"
                    />
                  </template>
                </template>
                <template v-if="column.key === 'cost_type_txt'">
                  <span>{{ record?.cost_type_txt || '--' }}</span>
                </template>
                <template v-if="column.key === 'remark'">
                  <template v-if="viewType == 'view'">
                    <span>{{ text }}</span>
                  </template>
                  <template v-else>
                    <a-textarea
                      v-model:value="record.remark"
                      placeholder="请输入账单备注"
                      :auto-size="{ minRows: 1, maxRows: 3 }"
                    />
                  </template>
                </template>
              </template>
            </a-table>
            <a-alert
              :message="'合计需付：' + Math.abs(prestoreTotal).toFixed(2) + '元'"
              type="info"
            />
          </a-card>
        </a-col>
      </a-row>
      <!--   附件   -->
      <a-row :gutter="12">
        <a-col :span="24" class="mt-10">
          <attachment-info
              :params="attachParams"
              :object="false"
              @getObjectId="getObjectId"
          />
        </a-col>
      </a-row>
    </section>

    <section class="header" id="footer" v-if="viewType == 'edit'">
      <a-page-header
        class="demo-page-header"
        style="border: 1px solid rgb(235, 237, 240)"
        title=""
        sub-title=""
      >
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div style="display: flex; align-items: center">
            <InfoCircleFilled style="font-size: 16px; color: #2681f3" />
            <div class="total-box" style="margin-left: 10px">
              <div class="total-item">
                <span class="total-title">合计应收：</span
                ><span class="total-num">{{
                  Math.abs(positiveTotal).toFixed(2)
                }}</span
              >元
              </div>
              <div class="total-item">
                <span class="total-title">合计应付：</span
                ><span class="total-num">{{
                  Math.abs(negativeTotal).toFixed(2)
                }}</span
              >元
              </div>
<!--              <div class="total-item">-->
<!--                <span class="total-title">{{ summaryTotalStatus }}</span-->
<!--                ><span class="total-num">{{-->
<!--                  Math.abs(summaryTotal).toFixed(2)-->
<!--                }}</span-->
<!--              >元-->
<!--              </div>-->
            </div>
          </div>
          <a-button
            @click="submitNewRetreat"
            :loading="submitNewRetreatLoading"
            type="primary"
            >{{viewForm == 'contractRetreat' ? '提交&生成账单' : '提交'}}</a-button
          >
        </div>
      </a-page-header>
    </section>

    <edit-tag
      @closeTag="editTagClose"
      @success="editSuccess"
      :visible="editVisible"
    ></edit-tag>

    <!--  退租添加收款  -->
    <NewIncomeBillDrawer
      :visible="addIncomeBillVisible"
      :ownerInfo="{
        name: mainInfo.owner_name,
        id: mainInfo.owner_id,
      }"
      useType="retreat"
      :useInfo="mainInfo"
      @cancel="addIncomeBillVisible = false"
      @success="addBillSuccess"
    />

    <!--  退租添加付款  -->
    <NewPaymentBillDrawer
      :visible="addPaymentBillVisible"
      :ownerInfo="{
        name: mainInfo.owner_name,
        id: mainInfo.owner_id,
      }"
      useType="retreat"
      :useInfo="mainInfo"
      @cancel="addPaymentBillVisible = false"
      @success="addBillSuccess"
    />

    <retreat-template
      @close="retreatTemplateClose"
      @success="retreatTemplateSuccess"
      :visible="templateModalVisible"
      :list="templateList"
      :loading="downloadTemplateLoading"
      v-if="templateList.length > 0"
    ></retreat-template>

    <!--  流水退款配置  -->
    <RefundConfigModal
      :visible="refundVisible"
      @handleSettingSuccess="handleRefundCancel"
      @handleCancel="handleRefundCancel"
    />

    <!--  罚没弹框  -->
    <ForfeitModal
      :visible="forfeitVisible"
      :forfeitInfo="forfeitInfo"
      @handleCancel="handleForfeitCancel"
      @handleOk="handleForfeitOk"
    />

    <!--  罚没记录  -->
    <ForfeitRecordDrawer
      :viewType="viewType"
      :visible="forfeitRecordVisible"
      :recordList="forfeitRecordInfo?.confiscations || []"
      @deleteOk="handleForfeitRecordDelete"
      @handleClose="handleForfeitRecordClose"
    />

    <!-- 账单详情 -->
    <BillDetailDrawer
      :visible="billDetailVisible"
      :id="billDetailId"
      @cancel="billDetailCancel"
    />

    <!--  结转明细  -->
    <CarryOverMoreDetail
      :visible="carryDetailVisible"
      :id="billDetailId"
      @handleCancel="carryDetailVisible = false"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  watch,
  h,
  computed,
  createVNode,
  reactive,
  toRefs,
  defineAsyncComponent,
} from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate } from "vue-router";
import request from "../../../common/utils/request";
import { FileTwoTone } from "@ant-design/icons-vue";
import moment from "moment";
import { TextTip } from "bl-common-vue3";
import CheckedBuild from "../../../components/contract/CheckedBuild/index.vue";
import EditTag from "./EditTag.vue";
import {
  InfoCircleFilled,
  DeleteOutlined,
  ExclamationCircleOutlined,
  SyncOutlined,
} from "@ant-design/icons-vue";
import { Modal } from "ant-design-vue";
import { Form, message } from "ant-design-vue";
const useForm = Form.useForm;

import RetreatTemplate from "./retreatTemplate.vue";
import utils from "@/common/utils/utils";
import _ from "lodash";
import RefundConfigModal from "@/views/bill/BillTurnover/modules/RefundConfigModal.vue";
import ForfeitModal from "@/views/bill/NewRetreat/modules/ForfeitModal.vue";
import ForfeitRecordDrawer from "@/views/bill/NewRetreat/modules/ForfeitRecordDrawer.vue";
const BillDetailDrawer = defineAsyncComponent(() =>
  import("@/views/bill/BillDetail/modules/BillDetailDrawer.vue")
);
import CarryOverMoreDetail from "@/views/bill/NewRetreat/modules/CarryOverMoreDetail.vue";
import AttachmentInfo from "@/components/contract/AttachmentInfo/index.vue";
import NewIncomeBillDrawer from "@/views/bill/NewBill/modules/NewIncomeBillDrawer.vue";
import NewPaymentBillDrawer from "@/views/bill/NewBill/modules/NewPaymentBillDrawer.vue";
export default defineComponent({
  name: "newRetreat",
  components: {
    AttachmentInfo,
    RefundConfigModal,
    FileTwoTone,
    TextTip,
    CheckedBuild,
    EditTag,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    NewIncomeBillDrawer,
    NewPaymentBillDrawer,
    InfoCircleFilled,
    DeleteOutlined,
    RetreatTemplate,
    SyncOutlined,
    ForfeitModal,
    ForfeitRecordDrawer,
    BillDetailDrawer,
    CarryOverMoreDetail,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();
    const notBack = $route.query.noBack;
    const id = ref(Number($route.query.id));
    const ownerId = ref(Number($route.query.owner_id));
    const viewType = ref($route.query.type);
    const viewForm = ref($route.query.form);
    console.log("viewTypeviewTypeviewType", viewType.value);

    // viewType = "view" ：浏览模式
    // viewType = "edit" ：编辑模式

    const billColumns = ref([]);

    const mainInfo = ref({});
    const buildBindInfo = ref({});
    const retreatTypeList = ref([]);
    const timeoutDay = ref(0);
    const billIds = ref([]);
    const bondIds = ref([]);

    const state = reactive({
      prestoreLoading: false,
      prestoreData: [],
      energyData: [],
      energyLoading: false,
      energyColumns: [],
      refundVisible: false,
      bondColumns: [],
      forfeitInfo: {},
      forfeitVisible: false,
      forfeitRecordVisible: false,
      forfeitRecordInfo: {},
      billDetailVisible: false,
      billDetailId: 0,
      carryDetailVisible: false,
      attachParams: {
        type: 1,
      },
      object_id:'',
    });

    const getObjectId = (id) => {
      state.object_id = id;
    };

    const getTableList = (type) => {
      // 账单结算
      getBillData(billIds.value);
      // 保证金
      if (type !== 'energy') {
        getBondData(bondIds.value);
      }
      if (viewType.value !== "view") {
        // 预存费用
        getPrestoreCost();
        // 水电信息
        getEnergyData();
      }
    };
    const getBasicInfo = () => {
      if (viewType.value == "view") {
        request
          .get("/org", "/retreat/getRetreatAgree", {
            contract_id: id.value,
          })
          .then((res) => {
            mainInfo.value = res.returnData.mainInfo;
            buildBindInfo.value = res.returnData.mainInfo.build_bind;
            retreatTypeList.value = res.returnData.retreatInfo.retreatType;
            modelRef.retreatType =
              res.returnData.retreatInfo.retreatData.retreat_type;
            modelRef.retreatDate = moment(
              res.returnData.retreatInfo.retreatData.retreat_date
            );
            modelRef.addressChangeDate = moment(
              res.returnData.retreatInfo.retreatData.bbc_change_date
            );
            modelRef.signDate = moment(
              res.returnData.retreatInfo.retreatData.apply_retreat_date
            );
            modelRef.retreatReason =
              res.returnData.retreatInfo.retreatData.retreat_reason;
            buildId.value = res.returnData.mainInfo.build_id;

            billIds.value = res.returnData.agreeBill;
            bondIds.value = res.returnData.agreeBond;
            let preData = _.cloneDeep(res.returnData?.retreatInfo?.retreatData?.prestore_info || []);
            state.prestoreData = preData.map((v) => {
              v.nomatch_price = "0.00";
              v.receivable_payment = "0.00";
              v.actual_retreat = "0.00";
              return v;
            });
            state.energyData = res.returnData?.retreatInfo?.retreatData?.energy_info || [];
          })
          .finally(() => {
            getTableList();
          });
      } else {
        request
          .get("/org", "/contract/retreatInfo", {
            contract_id: id.value,
          })
          .then((res) => {
            mainInfo.value = res.info.mainInfo;
            buildBindInfo.value = res.info.mainInfo.build_bind;
            retreatTypeList.value = res.info.retreatInfo.retreatType;
            timeoutDay.value = res.info.timeoutDay;
            if (res.info.timeoutDay > 0) {
              modelRef.retreatDate = moment(res.info.mainInfo.lease_endtime);
              modelRef.signDate = moment(res.info.mainInfo.lease_endtime);
            } else {
              if ($route.query.retreat_date) {
                modelRef.retreatDate = moment($route.query.retreat_date);
              }
              if ($route.query.retreat_type) {
                modelRef.retreatType = Number($route.query.retreat_type);
              }
            }
          })
          .finally(() => {
            getTableList();
          });
      }
    };

    const reasonList = ref([]);
    const getReasonList = () => {
      request
        .get("/org", "/contract/retreat/termination", {
          page: 1,
          pageSize: 99,
        })
        .then((res) => {
          reasonList.value = res.list;
        });
    };

    const editVisible = ref(false);
    const addIncomeBillVisible = ref(false);
    const addPaymentBillVisible = ref(false);

    const editTagClose = () => {
      editVisible.value = false;
    };

    const editSuccess = () => {
      editTagClose();
      getReasonList();
    };

    const addBillClose = () => {
      addIncomeBillVisible.value = false;
      addPaymentBillVisible.value = false;
    };

    const addBillSuccess = (data) => {
      addBillClose();
      let sourceData = _.cloneDeep(data);
      if (sourceData.bill_type == 1) {
        sourceData.pay_type = "income";
      } else {
        sourceData.pay_type = "pay";
      }
      sourceData.pre_receivable_payment = '0.00';
      billData.value.push(sourceData);
    };

    const showBillModal1 = () => {
      addIncomeBillVisible.value = true;
    };

    const showBillModal2 = () => {
      addPaymentBillVisible.value = true;
    };

    const modelRef = reactive({
      retreatType: null,
      retreatDate: moment(),
      addressChangeDate: "",
      signDate: moment(),
      retreatReason: [],
    });

    const rulesRef = reactive({
      retreatType: [{ required: true, message: "标签名称为必填项" }],
      retreatDate: [{ required: true, message: "标签名称为必填项" }],
      addressChangeDate: [{ required: false, message: "标签名称为必填项" }],
      signDate: [{ required: false, message: "标签名称为必填项" }],
      retreatReason: [{ required: true, message: "标签名称为必填项" }],
    });

    const { validate, validateInfos } = useForm(modelRef, rulesRef);

    const endOpen = ref(false);
    const signDate = computed(() => {
      return modelRef.signDate;
    });
    // const disabledStartDate = (signDate) => {
    //   if (!signDate || !modelRef.retreatDate) {
    //     return false;
    //   }
    //   //协议签订日期不能在退租日期之后，但可以在当天，时间戳+1天（一天=86400000）
    //   let startDate = "";
    //   if (modelRef.retreatDate._isAMomentObject) {
    //     if (modelRef.retreatDate.valueOf() < Date.now()) {
    //       startDate = modelRef.retreatDate.valueOf() + 86400000;
    //     } else {
    //       startDate = modelRef.retreatDate.valueOf();
    //     }
    //   } else {
    //     startDate = Date.now();
    //   }
    //   return signDate.valueOf() > startDate;
    // };

    const disabledStartDate = (current) => {
      return current > moment(modelRef.retreatDate).endOf("days");
    };

    const handleRetreatDateOpenChange = (open) => {
      endOpen.value = open;
      console.log("openopenopen", modelRef.retreatDate, modelRef.signDate);
    };

    const handleRetreatDateChange = (date, dateString) => {
      console.log("dateString", dateString);
      // 签订日期必须在退租日期之前
      if (
        !dateString ||
        (dateString &&
          modelRef.signDate &&
          new Date(dateString) < new Date(modelRef.signDate))
      ) {
        modelRef.signDate = "";
      }
      if (dateString) {
        request
          .post("/org", "/create/getRetreatBill", {
            contract_id: id.value,
            retreat_date: dateString,
          })
          .then((res) => {
            // 处理list每一条的应收付金额
            res.list.map((item) => {
              if (viewType.value == "edit") {
                item.receivable_payment_date = moment(
                  item.receivable_payment_date
                );
                item.pre_receivable_payment = item.receivable_payment;
              }
              // 如果退租日期在账单开始日期之前，则为0 (处理得应收金额) (应收/付金额)
              if (minusDate(modelRef.retreatDate, item.start_date) < 0) {
                item.receivable_payment = 0;
              } else if (minusDate(modelRef.retreatDate, item.end_date) >= 0) {
                // 如果退租日期在账单开始日期之后，不计算，展示原始数据
              } else {
                // 如果退租日期在账单开始日期到结束之间，公式计算
                item.receivable_payment = calcReceivedMoney(item);
              }
              onReceivableInput(item);
              item.before_amount = item.receivable_payment;
            });
            billData.value = res.list;
          });
      } else {
        billData.value = [];
      }
    };

    watch(signDate, () => {
      console.log("signDate", signDate.value);
    });
    watch(modelRef.retreatDate, () => {
      console.log("retreatDate", modelRef.retreatDate);
    });

    // 自定义行
    const billCustomRow = (record, index) => {
      // 浏览模式点击进入账单详情页
      if (viewType.value == "view") {
        return {
          style: {
            cursor: "pointer",
          },
          onClick: (e) => {
            $router.push({
              name: "billDetail",
              query: { billId: record.id },
            });
          },
        };
      }
    };

    // 自定义行
    const bondCustomRow = (record, index) => {
      // 浏览模式点击进入账单详情页
      if (viewType.value == "view") {
        return {
          style: {
            cursor: "pointer",
          },
          onClick: (e) => {
            $router.push({
              name: "billDetail",
              query: { billId: record.id },
            });
          },
        };
      }
    };

    const streamCustomRow = (record, index) => {
      // 浏览模式点击进入账单详情页
      if (viewType.value == "view") {
        return {
          style: {
            cursor: "pointer",
          },
          onClick: (e) => {
            $router.push({
              name: "turnoverDetail",
              query: { tId: record.id },
            });
          },
        };
      }
    }

    const billTotalStatus = computed(() => {
      if (billTotal.value >= 0) {
        return "合计需收：";
      } else {
        return "合计需付：";
      }
    });

    // 账单total
    const billTotal = computed(() => {
      let tmpTotal = 0;
      billData.value.map((item, index) => {
        item.actual_payment = item.actual_payment || "0.00";
        let tmp = 0;
        // 实收-转出+转入
        let actualAmount = utils.countSum([
          Number(item.actual_payment),
          Number(item.into_amount),
          -Number(item?.out_amount || 0),
        ]);
        tmp = utils.countSum([
          Number(item.receivable_payment),
          -Number(actualAmount),
        ]);
        if (
          item.pay_type == 'pay' &&
          tmp >= 0
        ) {
          tmp = utils.countSum([
            0,
            -Number(tmp),
          ]);
        }
        tmpTotal = utils.countSum([tmpTotal, tmp, Number(item.need_latefee)]);
      });
      return tmpTotal;
    });

    // 预存total
    const prestoreTotal = computed(() => {
      let tmpTotal = 0;
      state.prestoreData.map((item, index) => {
        item.actual_payment = item.actual_payment || "0.00";
        let tmp = 0;
        tmp = Number(item.actual_retreat);
        if (
          item.bill_type == 2
        ) {
          tmp = 0 - tmp;
        }
        tmpTotal = utils.countSum([tmpTotal, tmp]);
      });
      return tmpTotal;
    });

    const bondTotalStatus = computed(() => {
      if (bondTotal.value >= 0) {
        return "合计需收：";
      } else {
        return "合计需付：";
      }
    });

    // 保证金total
    const bondTotal = computed(() => {
      let tmpTotal = 0;
      bondData.value.map((item, index) => {
        tmpTotal = utils.countSum([tmpTotal, -Number(item.receivable_payment), Number(item.need_latefee)]);
      });
      return tmpTotal;
    });

    // 总计
    const summaryTotal = computed(() => {
      return utils.countSum([billTotal.value, bondTotal.value, prestoreTotal.value]);
    });

    const summaryTotalStatus = computed(() => {
      if (summaryTotal.value >= 0) {
        return "合计需收：";
      } else {
        return "合计需付：";
      }
    });

    // positive 需收 total
    const positiveTotal = computed(() => {
      let tmpTotal = 0;
      if (billTotal.value > 0) {
        tmpTotal = utils.countSum([tmpTotal, billTotal.value])
      }
      if (bondTotal.value > 0) {
        tmpTotal = utils.countSum([tmpTotal, bondTotal.value])
      }
      return tmpTotal;
    });

    // negative 需付 total
    const negativeTotal = computed(() => {
      let tmpTotal = 0;
      if (billTotal.value < 0) {
        tmpTotal = utils.countSum([tmpTotal, billTotal.value])
      }
      if (bondTotal.value < 0) {
        tmpTotal = utils.countSum([tmpTotal, bondTotal.value])
      }
      if (prestoreTotal.value < 0) {
        tmpTotal = utils.countSum([tmpTotal, prestoreTotal.value])
      }
      return tmpTotal;
    });

    const billData = ref([]);
    const billLoading = ref(false);
    const bondData = ref([]);
    const bondLoading = ref(false);

    const getBillData = (billIds) => {
      billLoading.value = true;
      request
        .post("/org", "/create/getRetreatBill", {
          contract_id: id.value,
          retreat_date: moment().format("YYYY-MM-DD"),
          agreeBill: billIds || [],
        })
        .then((res) => {
          // 处理list每一条的应收付金额
          res.list.forEach((item) => {
            if (viewType.value == "edit") {
              item.receivable_payment_date = moment(
                item.receivable_payment_date
              );
              item.pre_receivable_payment = item.receivable_payment;
              item.start_need_latefee = item.need_latefee || 0;
              // 如果退租日期在账单开始日期之前，则为0 (处理得应收金额) (应收/付金额)
              if (minusDate(modelRef.retreatDate, item.start_date) < 0) {
                item.receivable_payment = "0.00";
              } else if (minusDate(modelRef.retreatDate, item.end_date) >= 0) {
                // 如果退租日期在账单开始日期之后，不计算，展示原始数据
              } else {
                // 如果退租日期在账单开始日期到结束之间，公式计算
                item.receivable_payment = calcReceivedMoney(item);
              }
              onReceivableInput(item);
              item.before_amount = item.receivable_payment;
            }
          });
          billData.value = res.list;
          console.log(" billData.value", billData.value);
          billLoading.value = false;
        });
    };
    const getBondData = (bondIds) => {
      bondLoading.value = true;
      request
        .post("/org", "/create/getRetreatBond", {
          contract_id: id.value,
          agreeBond: bondIds || [],
        })
        .then((res) => {
          if (res.list.length > 0) {
            res.list.map((item) => {
              item.bill_receivable_payment = item.receivable_payment;
              item.actual_payment = item.actual_payment || "0.00"; // 实收金额(多少就是多少)
              item.actual_retreat = utils.countSum([Number(item.actual_payment), Number(item.into_amount || 0), -Number(item.out_amount || 0)]) //  需付金额 = 实收金额 + 转入金额 - 转出金额
              item.receivable_payment = item.actual_retreat || "0.00"; //  应付
              item.start_receivable_payment = item.receivable_payment; // 原始的应付
              item.bill_type = 2;
              item.start_need_latefee = item.need_latefee || 0;
              if (viewType.value == "edit") {
                item.receivable_payment_date = moment(
                  item.receivable_payment_date
                );
              }
            });
          }
          bondData.value = res.list;
          bondLoading.value = false;
        });
    };

    // 预存费用
    const getPrestoreCost = () => {
      state.prestoreLoading = true
      request
        .get("/org", "/contract/owner/prestoreCostList", {
          contract_id: id.value,
        })
        .then((res) => {
          let list = _.cloneDeep(res.list) || [];
          if (list.length > 0) {
            list = list.map((item) => {
              item.receivable_payment = item.nomatch_price || "0.00";
              item.actual_payment = item.amount || "0.00";
              item.actual_retreat = Number(item.receivable_payment).toFixed(2)
                .toString();
              item.bill_type = 2;
              item.receivable_payment_date = moment();
              item.cost_name = item.single_type ?  `专项-${item.single_type_txt}` : '非专项预存';
              item.before_amount = item.receivable_payment; // 修改前金额
              return item
            });
          }
          state.prestoreData = list || [];
          state.prestoreLoading = false;
        }).catch((err) => {
        state.prestoreLoading = false;
          if (err.code == 10001) {
            Modal.warning({
              title: "提示",
              content: err.msg || "流水退款配置未设置,请先设置",
              icon: () => createVNode(ExclamationCircleOutlined),
              centered: true,
              okText: () => "立即设置",
              onOk() {
                state.refundVisible = true;
              },
            });
          }
      });
    };

    const handleRefundCancel = () => {
      state.refundVisible = false;
      getPrestoreCost();
    };

    // 水电信息
    const getEnergyData = () => {
      state.energyLoading = true;
      let rooms = _.cloneDeep(mainInfo.value?.build_bind?.room || []);
      let roomIds = rooms.map((v) => {return v.id});
      request
        .get("/work_energy", "/energy/getEnergyListByRoomId", {
          village_id: mainInfo.value?.village_id || 0,
          room_id: roomIds.join(",")
        })
        .then((res) => {
          let list = res?.list || [];
          state.energyData = list.map((v) => {
            return {
              id: v?.id,
              name: v?.name || "", // 表名称
              type: v?.type,
              type_name: v?.type_txt || "",
              enter_num: _.isEmpty(v.energyRecord)
                ? v?.original_reading
                : v?.energyRecord?.last_number,
              cost_name: v?.energyTypeData?.cost_type_txt || "",
              unit_price: v?.energyRoomPrice?.is_stage_price
                ? ""
                : v?.energyRoomPrice?.unit_price, // 是阶梯价为''  不是阶梯价为 unit_price
              price_unit: v?.energyTypeData?.unit || "", // 计费单位
              is_stage_price: v?.energyRoomPrice?.is_stage_price,
              payment_type: v?.payment_type,
              payment_type_txt: v?.payment_type_txt,
              current_remaining: v?.current_remaining,
              property_device_id: v?.property_device_id,
              last_time: v?.last_time,
              stage_price: v?.energyRoomPrice?.stage_price,
              canGeneratedOrder: v?.canGeneratedOrder,
              total_price: v?.total_price,
            };
          });
          state.energyLoading = false;
        });
    };

    // 计算【账单】每一项的应收付金额
    // 公式：原账单应收付金额×【（退租日期-计租开始日期+1)/(计租结束日期-计租开始日期+1）】
    const minusDate = (date1, date2) => {
      return moment(new Date(date1)).diff(new Date(date2), "day");
    };

    const calcReceivedMoney = (record) => {
      let percent =
        (minusDate(modelRef.retreatDate, record.start_date) + 1) /
        (minusDate(record.end_date, record.start_date) + 1);
      let money = (Number(record.receivable_payment) * percent).toFixed(2);
      return money;
    };

    // 提交
    const submitNewRetreatLoading = ref(false);
    const submitNewRetreat = () => {
      validate().then(() => {
        Modal.confirm({
          title: "确定进行退租吗？",
          icon: createVNode(ExclamationCircleOutlined),
          content: "",
          okText: "确定",
          cancelText: "取消",
          onOk() {
            submitNewRetreatLoading.value = true;
            let billResult = _.cloneDeep(billData.value);
            let bondResult = _.cloneDeep(bondData.value);
            let prestoreResult = _.cloneDeep(state.prestoreData);
            billResult.forEach((item) => {
              item.receivable_payment_date = moment(
                item.receivable_payment_date
              ).format("YYYY-MM-DD");
            });
            bondResult.forEach((item) => {
              item.receivable_payment_date = moment(
                item.receivable_payment_date
              ).format("YYYY-MM-DD");
            });
            prestoreResult.forEach((item) => {
              item.stream_id = item.id;
              item.receivable_payment_date = moment(
                item.receivable_payment_date
              ).format("YYYY-MM-DD");
            });
            let params = {
              contract_id: id.value,
              id: id.value,
              owner_id: ownerId.value,
              build_bind: mainInfo.value.build_bind,
              bill_info: billResult,
              bond_info: bondResult,
              prestore_info: prestoreResult,
              energy_info: _.cloneDeep(state.energyData),
              total_cost: {
                billReceivable: billTotal.value,
                bondReceivable: bondTotal.value,
                prestoreReceivable: prestoreTotal.value,
                receivableTotal: summaryTotal.value,
              },
              retreat_type: modelRef.retreatType,
              retreat_date: moment(modelRef.retreatDate).format("YYYY-MM-DD"),
              bcc_change_date: modelRef.addressChangeDate
                ? moment(modelRef.addressChangeDate).format("YYYY-MM-DD")
                : "",
              apply_retreat_date: modelRef.signDate
                ? moment(modelRef.signDate).format("YYYY-MM-DD")
                : "",
              retreat_reason: modelRef.retreatReason,
              object_id: state.object_id,
            }

            if (viewForm.value == 'contractRetreat') {
              request
                .post("/org", "/contract/owner/retreat", params)
                .then((res) => {
                  submitNewRetreatLoading.value = false;
                  message.success(res.msg || "保存成功");
                  setTimeout(() => {
                    if (window.__MICRO_APP_ENVIRONMENT__) {
                      const microId = window.microApp?.appName;
                      window.microApp.forceDispatch({
                        type: "SetMicroPagesDel",
                        info: {
                          microId: microId,
                        },
                      });
                    } else {
                      $router.go(-1);
                    }
                  }, 150);
                })
                .catch((err) => {});
            } else {
              request
                .post("/org", "/create/contractRetreat", params)
                .then((res) => {
                  submitNewRetreatLoading.value = false;
                  message.success("已提交退租审批");
                  setTimeout(() => {
                    if (window.__MICRO_APP_ENVIRONMENT__) {
                      const microId = window.microApp?.appName;
                      window.microApp.forceDispatch({
                        type: "SetMicroPagesDel",
                        info: {
                          microId: microId,
                        },
                      });
                    } else {
                      $router.go(-1);
                    }
                  }, 150);
                })
                .catch((err) => {});
            }
          },
        });
      });
    };

    // 生成打印模板
    const buildId = ref(0);
    const templateList = ref([]);
    const templateModalVisible = ref(false);
    const createPrintModel = () => {
      request
        .get("/org", "/contract/retreatTemplate", {
          buildId: buildId.value,
        })
        .then((res) => {
          if (res.list.length > 0) {
            templateList.value = res.list;
            templateModalVisible.value = true;
            console.log("templateList.value ", templateList.value);
          } else {
            Modal.confirm({
              title: "提示",
              icon: createVNode(ExclamationCircleOutlined),
              content: "该楼宇还没有配置合同退租协议打印模板",
              okText: "立即前往",
              cancelText: "取消",
              onOk() {
                $router.push({
                  name: "retreatContractList",
                });
              },
            });
          }
        })
        .catch((err) => {
          Modal.confirm({
            title: "提示",
            icon: createVNode(ExclamationCircleOutlined),
            content: "该楼宇还没有配置合同退租协议打印模板",
            okText: "立即前往",
            cancelText: "取消",
            onOk() {
              $router.push({
                name: "retreatContractList",
              });
            },
          });
        });
    };

    const retreatTemplateClose = () => {
      templateModalVisible.value = false;
    };

    const downloadTemplateLoading = ref(false);

    const retreatTemplateSuccess = (templateId) => {
      downloadTemplateLoading.value = true;
      request
        .post("/org", "/create/applyRetreatTemplate", {
          contract_id: id.value,
          template_id: templateId,
        })
        .then((res) => {
          templateDownloadInfo.value = res.result;
          if (res.result) {
            downloadTemplateLoading.value = false;
            retreatTemplateClose();
            let info = {
              type: "selectDownloadFiles",
              url: res.result.fileUrl,
            };
            window.microApp.forceDispatch(info);
          }
        });
    };

    const templateDownloadInfo = ref({});
    const init = () => {
      getBasicInfo();
      getReasonList();
    };

    init();

    /* 账单结算计算公式 */
    const onReceivableInput = (record) => {
      // 需收 = 应收-（实收-转出+转入）
      // 实收-转出+转入
      let actualAmount = utils.countSum([
        Number(record.actual_payment),
        Number(record.into_amount),
        -Number(record?.out_amount || 0),
      ]);
      let amount = utils.countSum([
        Number(record.receivable_payment),
        -Number(actualAmount),
      ]);
      if (viewType.value == "edit") {
        record.actual_retreat = Math.abs(amount)
          .toFixed(2)
          .toString();
      }
      if (record?.bill_type == 2) {
        record.pay_type = 'pay';
      } else {
        if (
          amount >=
          0
        ) {
          record.pay_type = 'income';
        } else {
          record.pay_type = 'pay';
        }
      }
    };

    const onPrestoreReceivableInput = (record) => {
      if (viewType.value == "edit") {
        record.actual_retreat = Number(record.receivable_payment).toFixed(2).toString();
      }
    };

    const deleteAppendRecord = (index) => {
      Modal.confirm({
        title: "确认删除吗？",
        icon: createVNode(ExclamationCircleOutlined),
        content: "",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          billData.value.splice(index, 1);
        },
      });
    };

    const downloadFile = (fileUrl) => {
      let info = {
        type: "selectDownloadFiles",
        url: fileUrl,
      };
      window.microApp.forceDispatch(info);
    };

    // 抄表
    const getEnergyRead = (record) => {
      request
        .post("/work_energy", "/device/shimoMeter/read", {
          equipNumber: record.property_device_id,
        })
        .then((res) => {
          message.success(res.message || '操作成功');
          getEnergyData();
        });
    };

    // 后付费水电表抄表
    const getEnergyReading = (record) => {
      request
        .post("/work_energy", "/energy/bill/meterReading", {
          id: record.id,
        })
        .then((res) => {
          message.success(res.msg || "操作成功");
          getEnergyData();
        }).catch((err) => {
        if (err.code == 3000) {
          Modal.info({
            title: "提醒",
            content: err?.msg || "当前未绑定水电价格标准，请添加对应位置的价格标准后再进行抄表",
            centered: true,
            okText: () => "知道了",
          });
        }
      });
    };

    const getEnergyBill = (type, record) => {
      if (type == 'pay') {
        // 付款单
        request
          .post("/work_energy", "/energy/bill/generatePaymentOrder", {id: record.id, owner_id: ownerId.value, total_price: record.total_price})
          .then((res) => {
            message.success(res.msg || '操作成功');
            getTableList('energy');
          });
      } else {
        // 收款单
        request
          .post("/work_energy", "/energy/bill/generateReceiptOrder", {id: record.id})
          .then((res) => {
            message.success(res.msg || '操作成功');
            getTableList('energy');
          });
      }
    };

    /* 查看结转明细 */
    const viewCarryOver = (record) => {
      state.billDetailId = record.id;
      state.carryDetailVisible = true;
    };

    /* 查看罚没明细 */
    const viewForfeit = (record) => {
      state.forfeitRecordInfo = record;
      state.forfeitRecordVisible = true;
    };

    /* 罚没 */
    const forfeitBond = (record) => {
      if (record.receivable_payment <= 0) return;
      state.forfeitInfo = {
        id: record.id,
        max: record.receivable_payment,
      };
      state.forfeitVisible = true;
    };

    const handleForfeitCancel = () => {
      state.forfeitVisible = false;
      state.forfeitInfo = {};
    };

    const calculateBondData = (info) => {
      let forfeitData = info?.confiscations || [];
      let forfeitTotal = forfeitData.reduce((acc, cur) => utils.countSum([acc, Number(cur.amount)]), 0);
      info.forfeit_amount = forfeitTotal;
      info.receivable_payment = utils.countSum([info.start_receivable_payment, -Number(forfeitTotal)]);
      info.actual_retreat = info.receivable_payment;
    };

    const handleForfeitOk = (data) => {
      bondData.value.map((v) => {
        if (v.id == state.forfeitInfo.id) {
          if (!v.confiscations) {
            v.confiscations = [];
          }
          v.confiscations.push(data);
          calculateBondData(v);
        }
      })
      handleForfeitCancel();
    };

    const handleForfeitRecordDelete = () => {
      calculateBondData(state.forfeitRecordInfo);
    };

    const handleForfeitRecordClose = () => {
      state.forfeitRecordInfo = {};
      state.forfeitRecordVisible = false;
    };

    const viewBillDetail = (id) => {
      state.billDetailId = id;
      if (!state.billDetailId) return;
      state.billDetailVisible = true;
    };

    const billDetailCancel = () => {
      state.billDetailVisible = false;
      getTableList();
    };

    if (viewType.value == "view") {
      billColumns.value = [
        {
          title: "账单编号",
          dataIndex: "bill_number",
          key: "bill_number",
          width: 200,
          fixed: "left",
        },
        {
          title: "费用类型",
          dataIndex: "cost_type_txt",
          key: "cost_type_txt",
          width: 180,
        },
        {
          title: "计费周期",
          customRender: ({ text, record, index }) => {
            return record.start_date + " ~ " + record.end_date;
          },
          width: 200,
        },
        {
          title: "账单类型",
          dataIndex: "bill_type_txt",
          key: "bill_type_txt",
          width: 180,
        },
        {
          dataIndex: "receivable_payment",
          key: "receivable_payment",
          width: 240,
        },
        {
          title: "滞纳金",
          dataIndex: "need_latefee",
          key: "need_latefee",
          width: 180,
        },
        {
          title: "实收/付金额",
          dataIndex: "actual_payment",
          key: "actual_payment",
          width: 180,
        },
        {
          title: "结转",
          dataIndex: "carry_over",
          key: "carry_over",
          width: 220,
        },
        {
          title: "调整",
          dataIndex: "adjust_amount",
          key: "adjust_amount",
          width: 180,
          customRender: ({ text, record, index }) => {
            return text || "--";
          },
        },
        {
          title: "需收/付金额",
          dataIndex: "actual_retreat",
          key: "actual_retreat",
          width: 200,
        },
        {
          dataIndex: "receivable_payment_date",
          key: "receivable_payment_date",
          width: 180,
          fixed: "right",
        },
      ];
    } else {
      billColumns.value = [
        {
          title: "账单编号",
          dataIndex: "bill_number",
          key: "bill_number",
          width: 200,
          fixed: "left",
        },
        {
          title: "费用类型",
          dataIndex: "cost_type_txt",
          key: "cost_type_txt",
          width: 160,
        },
        {
          title: "计费周期",
          customRender: ({ text, record, index }) => {
            return record.start_date + " ~ " + record.end_date;
          },
          width: 200,
        },
        {
          dataIndex: "receivable_payment",
          key: "receivable_payment",
          width: 240,
        },
        {
          title: "滞纳金",
          dataIndex: "need_latefee",
          key: "need_latefee",
          width: 160,
        },
        {
          title: "实收/付金额",
          dataIndex: "actual_payment",
          key: "actual_payment",
          width: 160,
        },
        {
          title: "结转",
          dataIndex: "carry_over",
          key: "carry_over",
          width: 220,
        },
        {
          title: "调整",
          dataIndex: "adjust_amount",
          key: "adjust_amount",
          width: 160,
          customRender: ({ text, record, index }) => {
            return text || "--";
          },
        },
        {
          title: "需收/付金额",
          dataIndex: "actual_retreat",
          key: "actual_retreat",
          width: 200,
        },
        {
          dataIndex: "receivable_payment_date",
          key: "receivable_payment_date",
          width: 180,
          fixed: "right",
        },
      ];
    }

    if (viewType.value == "view") {
      state.energyColumns = _.cloneDeep(ENERGY_COLUMNS).filter((v) => v.key !== 'action')
    } else {
      state.energyColumns = _.cloneDeep(ENERGY_COLUMNS)
    }

    if (viewType.value == "view") {
      state.bondColumns = _.cloneDeep(BOND_COLUMNS).filter((v) => v.key !== 'action')
    } else {
      state.bondColumns = _.cloneDeep(BOND_COLUMNS)
    }

    return {
      ...toRefs(state),
      addIncomeBillVisible,
      addPaymentBillVisible,
      editVisible,
      mainInfo,
      buildBindInfo,
      retreatTypeList,
      reasonList,
      timeoutDay,
      editTagClose,
      editSuccess,
      endOpen,
      disabledStartDate,
      handleRetreatDateOpenChange,
      handleRetreatDateChange,

      billColumns,
      billData,
      billLoading,
      bondData,
      bondLoading,

      addBillClose,
      addBillSuccess,
      showBillModal1,
      showBillModal2,
      id,
      billTotal,
      bondTotal,
      summaryTotal,
      ownerId,

      billCustomRow,
      bondCustomRow,
      streamCustomRow,
      billTotalStatus,
      summaryTotalStatus,

      validateInfos,
      modelRef,

      submitNewRetreat,
      submitNewRetreatLoading,

      viewType,

      createPrintModel,

      templateList,
      templateModalVisible,
      retreatTemplateClose,
      retreatTemplateSuccess,
      templateDownloadInfo,

      onReceivableInput,
      deleteAppendRecord,
      downloadTemplateLoading,
      downloadFile,
      viewForm,
      prestoreColumns,
      prestoreTotal,
      onPrestoreReceivableInput,
      positiveTotal,
      negativeTotal,
      getEnergyData,
      getEnergyBill,
      getEnergyRead,
      getEnergyReading,
      bondTotalStatus,
      handleRefundCancel,
      viewCarryOver,
      viewForfeit,
      forfeitBond,
      handleForfeitCancel,
      handleForfeitOk,
      handleForfeitRecordDelete,
      handleForfeitRecordClose,
      viewBillDetail,
      billDetailCancel,
      getObjectId,

      notBack
    };
  },
});

const ENERGY_COLUMNS = [
  {
    title: "表名称",
    dataIndex: "name",
    key: "name",
    width: "15%",
  },
  {
    title: "表种类",
    dataIndex: "energyType",
    key: "energyType",
    width: "15%",
  },
  {
    title: "上期抄表读数",
    dataIndex: "enter_num",
    key: "enter_num",
  },
  {
    title: "上期抄表时间",
    dataIndex: "last_time",
    key: "last_time",
    customRender: ({ text, record, index }) => {
      return text || '--';
    },
  },
  {
    title: "对应费用类型",
    dataIndex: "cost_name",
    key: "cost_name",
    customRender: ({ text, record, index }) => {
      return text || '--';
    },
  },
  {
    title: "计费单价",
    dataIndex: "price",
    key: "price",
    customRender: ({record}) => {
      return record?.stage_price ? record.stage_price + '/' + record.price_unit : record?.unit_price ? '￥' + record?.unit_price + '/' + record.price_unit : record?.is_stage_price ? '阶梯价/' + record.price_unit : '--/' + record.price_unit;
    },
  },
  {
    title: "余量",
    dataIndex: "current_remaining",
    key: "current_remaining",
    customRender: ({ text, record, index }) => {
      return record?.payment_type ? text + ' ' + record.price_unit : "--";
    },
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    width: 220,
  },
];

const prestoreColumns = [
  {
    title: "专项预存",
    dataIndex: "cost_name",
    width: "8%",
  },
  {
    title: "预存金额",
    dataIndex: "amount",
    width: "8%",
  },
  {
    title: "剩余金额",
    dataIndex: "nomatch_price",
    width: "12%",
  },
  {
    title: "应退金额",
    dataIndex: "receivable_payment",
    key: "receivable_payment",
    width: "12%",
  },
  {
    title: "实收金额",
    dataIndex: "actual_payment",
    key: "actual_payment",
    width: "12%",
  },
  {
    dataIndex: "cost_type_txt",
    key: "cost_type_txt",
    width: "12%",
  },
  {
    dataIndex: "remark",
    key: "remark",
    width: "12%",
  },
  {
    title: "需退金额",
    dataIndex: "actual_retreat",
    key: "actual_retreat",
    width: "12%",
  },
  {
    title: "应退日期",
    dataIndex: "receivable_payment_date",
    key: "receivable_payment_date",
    width: "12%",
  },
];

const BOND_COLUMNS = [
  {
    title: "账单编号",
    dataIndex: "bill_number",
    key: "bill_number",
    fixed: "left",
    width: 200,
  },
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    width: 140,
  },
  {
    title: "计费周期",
    customRender: ({ text, record, index }) => {
      return record.start_date + " ~ " + record.end_date;
    },
    width: 200,
  },
  {
    title: "应收金额",
    dataIndex: "bill_receivable_payment",
    width: 160,
  },
  {
    title: "滞纳金",
    dataIndex: "need_latefee",
    key: "need_latefee",
    width: 140,
  },
  {
    title: "实收金额",
    dataIndex: "actual_payment",
    width: 140,
  },
  {
    title: "结转",
    dataIndex: "carry_over",
    key: "carry_over",
    width: 200,
  },
  {
    title: "罚没金额",
    dataIndex: "forfeit_amount",
    key: "forfeit_amount",
    width: 160,
  },
  {
    title: "应退金额",
    dataIndex: "receivable_payment",
    key: "receivable_payment",
    width: 140,
  },
  {
    title: "应退日期",
    dataIndex: "receivable_payment_date",
    key: "receivable_payment_date",
    width: 180,
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    width: 100,
    fixed: "right",
  },
];

</script>

<style lang="less" scoped>
.new-retreat {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    background-color: #fff;

    :deep(.ant-list-item-meta-avatar) {
      margin-right: 32px;
      margin-left: 16px;
      margin-top: 10px;
    }

    :deep(.ant-page-header) {
      padding-bottom: 0;
    }
    .hide-back{
      :deep(.ant-page-header-back) {
        display: none;
      }
    }
  }

  .content {
    flex: 1;
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    overflow-y: auto;
    overflow-x: auto;

    .bill-card {
      :deep(.ant-alert-info) {
        background-color: #fafafa;
        border: none;
      }

      :deep(.ant-alert-message) {
        text-align: right;
        padding-right: 10px;
      }
    }
  }

  #footer {
    :deep(.ant-page-header) {
      padding-bottom: 20px;
    }
  }
}
.total-item {
  margin-right: 10px;
}
.total-box {
  display: flex;
  font-weight: bold;
}
.total-num {
  margin: 0 5px;
  font-size: 18px;
  color: @primary-color;
}
</style>
